package com.chen.jwt.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.chen.jwt.enumToken.Token;
import com.chen.jwt.pojo.Users;
import com.chen.jwt.service.UserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.Optional;

/**
 * @Author xlj
 * @Date Created in  2023/2/15 15:53
 * @DESCRIPTION:
 * @Version V1.0
 */

@Component
public class HttpServletRequestToken {

   @Resource
   private UserService userService;

   @Resource
   private RedisTemplate redisTemplate;
   public Users getUser(HttpServletRequest request) throws Throwable {
      String token = request.getHeader(Token.TOKEN);
      Optional.ofNullable(token).orElseThrow(() -> new Throwable("token为空"));
      Object token1 = redisTemplate.opsForValue().get(Token.TOKEN);
      if (!(Objects.equals(token1, token))){
         throw new RuntimeException("token错误");
      }
      DecodedJWT decode = JWT.decode(token);
      String id = decode.getClaim(Token.ID).asString();
      int i = Integer.parseInt(id);
      Users user = userService.findUserById(i);
      if (user == null) {
          throw new IllegalArgumentException("用户为空");
      }
      return user;
   }
}
